import './style.less';

import * as R from 'ramda';

import { Button, Form, Input, message } from 'antd';
import React, { useCallback } from 'react';
import { useHistory, useLocation } from 'react-router-dom';

import Cookies from 'js-cookie';
import { DOMAIN } from '../../lib/constants';
import Icon from '../../components/Icon';
import { authentication } from '@/service/auth';
import { cssClass } from '@/utils/common';
import { unResWrapper } from '../../utils/common';
import { useRequest } from 'ahooks';

const loginCss = cssClass('login');
const Login = () => {
  const [form] = Form.useForm();
  const history = useHistory();
  const location = useLocation();
  const { run, loading } = useRequest(unResWrapper(authentication), {
    manual: true,
    throwOnError: true,
  });

  const submit = useCallback(() => {
    form
      .validateFields()
      .then(run)
      .then((token) => {
        message.success('登录成功', 1, () => {
          Cookies.set('token', token, {
            domain: DOMAIN,
          });
          if (location.query) {
            const { redirectUrl, redirectPath } = location.query;
            if (redirectUrl) {
              window.location.href = redirectUrl;
            } else {
              history.replace(redirectPath || '/dashboard');
            }
          } else {
            history.replace('/dashboard');
          }
        });
      });
  }, [run, form, history, location]);

  return (
    <div className={loginCss('wrap')}>
      <h2>欢迎来到{new Date().getFullYear()}</h2>
      <Form className={loginCss('form')} size="large" form={form}>
        <Form.Item name="account">
          <Input
            prefix={<Icon type="user-outlined" />}
            placeholder="请输入账号"
          />
        </Form.Item>
        <Form.Item name="password">
          <Input.Password
            prefix={<Icon type="lock-outlined" />}
            placeholder="请输入密码"
            onKeyDown={R.when(R.propEq('keyCode', 13), submit)}
          />
        </Form.Item>
        <Form.Item>
          <Button type="primary" block onClick={submit} loading={loading}>
            登录
          </Button>
        </Form.Item>
        <Form.Item>
          <Button
            type="primary"
            block
            ghost
            onClick={() => history.replace('/register')}
          >
            去注册
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default Login;
